package com.customers.controller;

import com.customers.entity.Message;
import com.customers.entity.User;
import com.customers.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//@WebServlet()
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User(null,username,password);



        //判断是否登录成功
        Message usermessage = null;
        try {
            UserService userService = (UserService)request.getServletContext().getAttribute("UserService");
            String sql = "userLogin";
            usermessage = userService.userlogin(user,sql);

//            usermessage = UserServic.userlogin(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(usermessage.getCode()==1){
            //成功,则重定向跳转首页
            request.setAttribute("user",usermessage.getObject());
            request.getSession().setAttribute("userSeccess",usermessage.getObject());
            response.sendRedirect("select.jsp");
        }
        else{
            //失败，则请求转发登录界面
            request.setAttribute("usermessage",usermessage);
            request.getRequestDispatcher("userlogin.jsp").forward(request,response);
        }
    }
}
